package com.nhh.v.service

import java.sql.Timestamp
import java.util.{Date, Calendar}

import com.nhh.exception.ServiceException
import com.nhh.v.dto.{MyExchangeInfo, HomeUserInfo}
import com.nhh.v.mapper.{NhhwakTownsMapper, NhhwakConfigMapper, NhhwakExchangeRecordsMapper}
import com.nhh.v.model.{NhhwakCoinDetails, NhhwakExchangeRecords, NhhwakConfig}
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
import org.springframework.transaction.annotation.Transactional

import scala.beans.BeanProperty

/**
  * Created by chenkaiming on 2018/9/9.
  */
@Service
class ExchangeService(@Autowired val exchangeMapper: NhhwakExchangeRecordsMapper,
                      @Autowired val usersService: UsersService,
                      @Autowired val nhhConfigMapper: NhhwakConfigMapper,
                      @Autowired val nhhwakTownsMapper: NhhwakTownsMapper,
                      @Autowired val nhhwakCoinDetailsService: NhhwakCoinDetailsSeivice) extends BaseService{

  def qrMyExchange(uid: String, pSize: String, pIndex: String): java.util.List[MyExchangeInfo] = {
    startPage(pIndex.toInt, pSize.toInt, false)
    exchangeMapper.qrMyExchange(uid)
  }

  @Transactional
  def exchangeCoins(uid: String, num: String): ResultData = {

    if (num.toDouble < 0) {
      throw new ServiceException("1", "对不起,兑换数量异常")
    } else {
      val user = usersService.getUserById(uid)

      Option(user) match {
        case None ⇒
          throw new ServiceException("3001", "用户信息获取失败")
        case _ ⇒
          val nhhwakConfig = nhhConfigMapper.getEth2NHHConfig()
          val consumeNhhCoins = num.toDouble * BigDecimal(nhhwakConfig.getEth2nhhrate)

          checkExchangeConfig(nhhwakConfig, num.toDouble)
          checkTownConfig(nhhwakConfig, user)
          checkUserConfig(nhhwakConfig, user, consumeNhhCoins)

          val exchangeMapperRecord = NhhwakExchangeRecords
            .builder()
            .userId(user.getId)
            .`type`("eth")
            .num(BigDecimal(num).bigDecimal)
            .consumeNhhcoins(consumeNhhCoins.bigDecimal)
            .status("processing")
            .source("exchange")
            .build()

          exchangeMapper.addExchangeRecord(exchangeMapperRecord)

          usersService.updateUserCoins(user.getId, BigDecimal(user.getNhhcoins) - consumeNhhCoins)

          val nhhwakCoinDetailsRecord = NhhwakCoinDetails
            .builder()
            .userId(user.getId)
            .nhhcoins(consumeNhhCoins.bigDecimal.negate)
            .status(true)
            .source("exchange")
            .relateId(exchangeMapperRecord.getId)
            .build()

          nhhwakCoinDetailsService.addCoinDetailsRecord(nhhwakCoinDetailsRecord)

          new ResultData()
      }

    }
  }

  private def checkExchangeConfig(nhhwakConfig: NhhwakConfig, num: Double): Unit = {
    val returnCode = "21003"
    if (BigDecimal(nhhwakConfig.getEth2nhhrate) <= 0 ||
      nhhwakConfig.getEth2nhhdays <= 0 ||
      BigDecimal(nhhwakConfig.getEth2nhhMinnum) > BigDecimal(nhhwakConfig.getEth2nhhMaxnum) ||
      BigDecimal(nhhwakConfig.getEth2nhhUserrate) > 1 ||
      BigDecimal(nhhwakConfig.getEth2nhhUserrate) < 0) {
      throw new ServiceException(returnCode, "兑换配置异常")
    } else if (num > BigDecimal(nhhwakConfig.getEth2nhhMaxnum) ||
      num < BigDecimal(nhhwakConfig.getEth2nhhMinnum)) {
      throw new ServiceException(returnCode, "您兑换额度不在合法范围内，无法兑换!")
    }
  }

  private def checkTownConfig(nhhwakConfig: NhhwakConfig, user: HomeUserInfo): Unit = {
    val returnCode = "21003"
    if (user.getTownRole != "lord") {
      throw new ServiceException(returnCode, "您还不是城主，无法兑换!")
    } else if (nhhwakTownsMapper.selectTownUserNumById(user.getTownId) < nhhwakConfig.getEth2nhhTownnumlowlimit) {
      throw new ServiceException(returnCode, "您的城池人数没达到要求，无法兑换!")
    } else if (usersService.getInviteUserNumById(user.getId) < nhhwakConfig.getEth2nhhInvuserlowlimit) {
      throw new ServiceException(returnCode, "您邀请的会员数没达到要求，无法兑换!")
    }
  }
  private def checkUserConfig(nhhwakConfig: NhhwakConfig, user: HomeUserInfo, consumeNhhCoins: BigDecimal): Unit = {
    if (consumeNhhCoins > user.getNhhcoins.toDouble * BigDecimal(nhhwakConfig.getEth2nhhUserrate)) {
      throw new ServiceException("21003", "您兑换额度已达到持仓上限，无法兑换!")
    } else if (consumeNhhCoins > user.getNhhcoins.toDouble) {
      throw new ServiceException("21005", "余额不足")
    } else {
      val cal = Calendar.getInstance
      cal.add(Calendar.DATE, - nhhwakConfig.getEth2nhhdays)
      val exchangeTimes = exchangeMapper.exchangeTimesByUid(user.getId, cal.getTime)
      if (exchangeTimes > 0) {
        throw new ServiceException("21004", s"${nhhwakConfig.getEth2nhhdays}天内只有一次兑换机会!")
      }
    }
  }

}
